package org.mspring.mlog.api.denglu;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.mspring.mlog.entity.Comment;
import org.mspring.mlog.entity.Post;
import org.mspring.mlog.service.CommentService;
import org.mspring.platform.denglu.api.DengluCommentApiService;
import org.mspring.platform.denglu.entity.DengluCommentSyncLog;
import org.mspring.platform.denglu.entity.dto.DengluComment;
import org.mspring.platform.denglu.service.DengluCommentSyncLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

;

/**
 * 登录评论同步服务
 *
 * @author Gao Youbo
 * @since 2014-05-27 13:28:47
 */
@Component
public class DengluCommentSyncService implements Runnable {

    private static final Logger log = LoggerFactory.getLogger(DengluCommentSyncService.class);

    private Thread thread;

    private DengluCommentSyncLogService dengluCommentSyncLogService;
    private DengluCommentApiService dengluCommentApiService;
    private CommentService commentService;

    private static final int batch = 50; // 单次同步数量
    private static final long interval = 1000 * 60 * 5; // 同步时间间隔:5分钟

    @Override
    public void run() {
        while (true) {
            try {
                int count = doSync();
                if (count < batch) { // 同步数量不足单次同步数量，暂停一下
                    threadSleep(interval);
                }
            } catch (Exception e) {
                log.error("灯鹭：评论同步失败", e);
                threadSleep(interval);
            }
        }
    }

    private void threadSleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            log.error(null, e);
        }
    }

    @PostConstruct
    protected void init() {
        thread = new Thread(this, "灯鹭：同步评论");
        thread.start();
    }

    @PreDestroy
    protected void destory() {
        if (thread != null) {
            thread.interrupt();
            thread = null;
        }
    }

    /**
     * 执行同步
     *
     * @return
     * @throws URISyntaxException
     * @throws IOException
     *             同步数量
     */
    public int doSync() throws IOException, URISyntaxException {
        long start = System.currentTimeMillis();
        int count = 0;
        long maxId = 0;
        DengluCommentSyncLog newLog = new DengluCommentSyncLog();
        try {
            DengluCommentSyncLog log = dengluCommentSyncLogService.findLastedSuccess();
            if (log != null) {
                maxId = log.getMaxId();
            }
            List<DengluComment> comments = dengluCommentApiService.getCommentList(maxId, batch);
            if (comments != null && comments.size() > 0) {
                for (DengluComment dengluComment : comments) {
                    Comment comment = parseComment(dengluComment);
                    commentService.insert(comment);
                    count++;
                    if (dengluComment.getCommentID() > maxId) {
                        maxId = dengluComment.getCommentID();
                    }
                }
            }
            newLog.setSuccess(true);
        } catch (Exception e) {
            log.error("灯鹭：同步失败", e);
            newLog.setSuccess(false);
        } finally {
            newLog.setCount(count);
            newLog.setSyncTime(new Date());
            newLog.setElapsed(System.currentTimeMillis() - start);
            newLog.setMaxId(maxId);
            dengluCommentSyncLogService.insert(newLog);
            log.info("灯鹭：同步完成。success={}, 数量={}, 耗时={}, maxId={}", newLog.isSuccess(), count, newLog.getElapsed(), maxId);
        }
        return count;
    }

    /**
     * 将灯鹭评论转换为系统评论
     *
     * @param dengluComment
     * @return
     */
    private Comment parseComment(DengluComment dengluComment) {
        Comment comment = new Comment();
        comment.setPost(new Post(dengluComment.getPostid()));
        comment.setContent(dengluComment.getContent());
        comment.setAuthor(dengluComment.getUserName());
        comment.setEmail(dengluComment.getUserEmail());
        comment.setUrl(dengluComment.getHomepage());
        comment.setPostIp(dengluComment.getIp());
        comment.setCreateTime(dengluComment.getCreateTime());
        comment.setDengluCommentId(dengluComment.getCommentID());
        if (dengluComment.getParent() != null && dengluComment.getParent().getCommentID() > 0) {
            Comment parent = commentService.getBy("dengluCommentId", dengluComment.getParent().getCommentID());
            if (parent == null) {
                log.warn("未找到灯鹭对应评论。dengluCommentId = {}", dengluComment.getParent().getCommentID());
            } else {
                comment.setParent(parent);
            }
        }
        String status = "";
        switch (dengluComment.getState()) {
            case 1:
                status = Comment.Status.WAIT_FOR_APPROVE;
                break;
            case 2:
                status = Comment.Status.SPAM;
                break;
            case 3:
                status = Comment.Status.RECYCLE;
                break;
            default:
                status = Comment.Status.APPROVED;
                break;
        }
        comment.setStatus(status);
        return comment;
    }

    @Autowired
    public void setDengluCommentSyncLogService(DengluCommentSyncLogService dengluCommentSyncLogService) {
        this.dengluCommentSyncLogService = dengluCommentSyncLogService;
    }

    @Autowired
    public void setDengluCommentApiService(DengluCommentApiService dengluCommentApiService) {
        this.dengluCommentApiService = dengluCommentApiService;
    }

    @Autowired
    public void setCommentService(CommentService commentService) {
        this.commentService = commentService;
    }

}
